﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using Example.Entities;
using Example.Transports.Customer;
using Zero.Frontend;

namespace Example.Frontend.Customers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class CustomerEditViewModel : Screen, IAsyncInicializable
    {
        private int? _customerID;
        private bool _create;
        private CustomersViewModel _openedFrom;

        private Customer _customer;

        public Customer Customer
        {
            get { return _customer; }
            set
            {
                if (_customer == value) return;

                _customer = value;
                NotifyOfPropertyChange(() => Customer);
            }
        }

        public IEnumerable<IResult> InicializeAsync()
        {
            return _customerID == null ? InitCreate() : InitEdit(_customerID.Value);
        }

        public void AsEditOf(CustomersViewModel parent, int? customerID = null)
        {
            _customerID = customerID;
            _openedFrom = parent;
        }

        private IEnumerable<IResult> InitCreate()
        {
            DisplayName = "Create customer";
            _create = true;

            Customer = new Customer { BirthDate = DateTime.Now };

            yield break;
        }

        private IEnumerable<IResult> InitEdit(int customerID)
        {
            DisplayName = "Edit customer";
            _create = false;

            var r = new GetCustomer(customerID).AsRequest(false);
            yield return r;

            _customer = r.Result.Customer;
        }

        public IEnumerable<IResult> Confirm()
        {
            if (!Customer.IsValid)
            {
                MessageBox.Show(Customer.ValidError);

                yield break;
            }

            yield return Show.Busy();

            var request = new SaveCustomer { Customer = Customer, Create = _create}.AsRequest();
            
            yield return request;

            if (request.Successful)
            {
                (Parent as IConductor).ActivateItem(_openedFrom);

                _openedFrom.ReloadCustomers(request.Result.NewCustomerID);

                TryClose(true);
            }
            else
            {
                MessageBox.Show(request.Error.ToString());
            }

            yield return Show.NotBusy();
        }

        public void Cancel()
        {
            TryClose(false);
        }
    }
}